﻿using DataAccessLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using Xceed.Wpf.Toolkit;
using System.Runtime.ExceptionServices;
using System.Data.SqlClient;

namespace GroepEF4
{
    /// <summary>
    /// Interaction logic for Algemeen.xaml
    /// </summary>
    public partial class Algemeen : MetroWindow
    {
        private string userID;

        public Algemeen(string userId)
        {
            this.userID = userId;
            InitializeComponent();
        }

        private void ToggleFlyout(int index)
        {
            var flyout = this.Flyouts.Items[index] as Flyout;
            if (flyout == null)
            {
                return;
            }

            flyout.IsOpen = !flyout.IsOpen;
        }

        private void addButton_Click(object sender, RoutedEventArgs e)
        {

            cboCompany.ItemsSource = DataAccessLayer.CompanyDB.ShowAll();
            cboLocatie.ItemsSource = DataAccessLayer.LocationDB.ShowAll();
            this.ToggleFlyout(0);
        }

        private async void removeButton_Click(object sender, RoutedEventArgs e)
        {

            var mySettings = new MetroDialogSettings()
            {
                AffirmativeButtonText = "Ja",
                NegativeButtonText = "Nee",
            };

            Reservation r = (Reservation)ReservatieGrid.SelectedItem;
            if (r == null)
            {
                await this.ShowMessageAsync("Fout!", "Je moet eerst een reservatie selecteren!");
            }
            else
            {
                MessageDialogResult result = await this.ShowMessageAsync("Reservatie verwijderen", "Weet je zeker dat je deze reservatie wil verwijderen?",
                MessageDialogStyle.AffirmativeAndNegative, mySettings);

                if (result != MessageDialogResult.Negative)
                {
                    int aantal = ReservationDB.DeleteReservation(r);
                    await this.ShowMessageAsync("Verwijderd", "De reservatie is verwijderd!");
                    ReservatieGrid.ItemsSource = DataAccessLayer.ReservationDB.GetReservationsUser(userID);
                }

                else
                {
                    await this.ShowMessageAsync("Niet verwijderd!", "De reservatie is NIET verwijderd!");
                }
            }
        }

        private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ContractLopendeGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsLopendUser(userID);
            ContractAfgelopenGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsAfgelopenUser(userID);
            ReservatieGrid.ItemsSource = DataAccessLayer.ReservationDB.GetReservationsUser(userID);
        }

        private async void AddReservation(object sender, RoutedEventArgs e)
        {
            try
            {
                Reservation r = new Reservation();
                string CompanyName = ((Company)cboCompany.SelectedItem).Name;
                r.CompanyId = DataAccessLayer.CompanyDB.GetCompanyIdByName(CompanyName);

                string LocationName = ((Location)cboLocatie.SelectedItem).Name;
                r.LocationId = DataAccessLayer.LocationDB.GetLocationIdByName(LocationName);

                r.StartDate = DateBegin.Value.Value;
                r.EndDate = DateEnd.Value.Value;

                DateTime vandaag = DateTime.Now;

                if (r.StartDate < vandaag)
                {
                    await this.ShowMessageAsync("Fout!", "De startdatum kan niet in het verleden liggen.");
                }
                else if(r.EndDate < r.StartDate)
                {
                    await this.ShowMessageAsync("Fout!", "De einddatum kan niet voor de startdatum liggen.");
                }
                else
                {
                    bool LocationAvailable = ReservationDB.LocationAvailable(r.LocationId, r.StartDate, r.EndDate);

                    if (LocationAvailable == false)
                    {
                        await this.ShowMessageAsync("Fout!", "De locatie is niet meer beschikbaar voor dit tijdstip!");
                    }
                    else
                    {
                        int aantal = ReservationDB.InsertReservation(r, userID);

                        if (aantal == 0)
                        {
                            await this.ShowMessageAsync("Fout!", "Er is geen reservatie toegevoegd.");
                        }
                        else
                        {
                            await this.ShowMessageAsync("Succes!", "De reservatie is toegevoegd!");
                        }
                        cboLocatie.Text = null;
                        cboCompany.Text = null;
                        DateBegin.Text = null;
                        DateEnd.Text = null;
                        this.ToggleFlyout(0);
                        ReservatieGrid.ItemsSource = DataAccessLayer.ReservationDB.GetReservationsUser(userID);
                    }
                }               
            }

            catch (InvalidOperationException ex)
            {
                string exception = "Gelieve alle velden in te vullen!";
                MessageboxReservation(exception);
            }

            catch (SqlException sqlEx)
            {
                string exception = sqlEx.Message;
                MessageboxReservation(exception);
            }

            catch (FormatException ex)
            {
                string exception = ex.ToString();
                MessageboxReservation(exception);
            }
            catch (Exception ex)
            {
                string exception = ex.ToString();
                MessageboxReservation(exception);
            }

            this.ToggleFlyout(0);
        }

        private void CancelReservation(object sender, RoutedEventArgs e)
        {
            cboLocatie.Text = null;
            cboCompany.Text = null;
            DateBegin.Text = null;
            DateEnd.Text = null;
            this.ToggleFlyout(0);
        }

        private async void MessageboxReservation(string ex)
        {
            await this.ShowMessageAsync("Fout!", ex);
        }

        private void CancelEdit(object sender, RoutedEventArgs e)
        {
            cboLocatie2.Text = null;
            cboCompany2.Text = null;
            DateBegin2.Text = null;
            DateEnd2.Text = null;
            this.ToggleFlyout(1);
        }

        private async void EditReservation(object sender, RoutedEventArgs e)
        {
            try
            {
                Reservation r = (Reservation)ReservatieGrid.SelectedItem;
                if (r == null)
                {
                    await this.ShowMessageAsync("Fout!", "Je moet eerst een reservatie selecteren!");
                }
                else
                {
                    string CompanyName = ((Company)cboCompany2.SelectedItem).Name;
                    r.CompanyId = DataAccessLayer.CompanyDB.GetCompanyIdByName(CompanyName);

                    string LocationName = ((Location)cboLocatie2.SelectedItem).Name;
                    r.LocationId = DataAccessLayer.LocationDB.GetLocationIdByName(LocationName);
                    r.StartDate = DateBegin2.Value.Value;
                    r.EndDate = DateEnd2.Value.Value;

                    int aantal = ReservationDB.UpdateReservation(r, userID);

                    if (aantal == 0)
                    {
                        await this.ShowMessageAsync("Fout!", "Er is geen reservatie aangepast.");
                    }
                    else
                    {
                        await this.ShowMessageAsync("Succes!", "De reservatie is aangepast.");
                    }
                }
                this.ToggleFlyout(1);
                ReservatieGrid.ItemsSource = DataAccessLayer.ReservationDB.GetReservationsUser(userID);
            }
            catch (InvalidOperationException ex)
            {
                string exception = "Gelieve alle velden in te vullen!";
                MessageboxReservation(exception);
            }

            catch (SqlException sqlEx)
            {
                string exception = "Gelieve alle velden in te vullen!";
                MessageboxReservation(exception);
            }

            catch (FormatException ex)
            {
                string exception = ex.ToString();
                MessageboxReservation(exception);
            }
            catch (Exception ex)
            {
                string exception = ex.ToString();
                MessageboxReservation(exception);
            }
            this.ToggleFlyout(1);
        }

        private async void EditButton_Click(object sender, RoutedEventArgs e)
        {
            Reservation r = (Reservation)ReservatieGrid.SelectedItem;
            if (r == null)
            {
                await this.ShowMessageAsync("Fout!", "Je moet eerst een reservatie selecteren!");
            }
            else
            {
                cboCompany2.ItemsSource = DataAccessLayer.CompanyDB.ShowAll();
                cboCompany2.SelectedValue = r.CompanyId;
                cboLocatie2.ItemsSource = DataAccessLayer.LocationDB.ShowAll();
                cboLocatie2.SelectedValue = r.LocationId;
                DateBegin2.Value = r.StartDate;
                DateEnd2.Value = r.EndDate;
                this.ToggleFlyout(1);
            }
        }

        private async void StopContract_Click(object sender, RoutedEventArgs e)
        {
            var mySettings = new MetroDialogSettings()
            {
                AffirmativeButtonText = "Ja",
                NegativeButtonText = "Nee",
            };

            Contract c = (Contract)ContractLopendeGrid.SelectedItem;
            if (c == null)
            {
                await this.ShowMessageAsync("Fout!", "Selecteer een opkomend of lopend contract");
            }
            else
            {
                MessageDialogResult result = await this.ShowMessageAsync("Contract stoppen", "Weet je zeker dat je dit contract wil stoppen?",
                MessageDialogStyle.AffirmativeAndNegative, mySettings);

                if (result != MessageDialogResult.Negative)
                {
                    bool ReservationControle = DataAccessLayer.ContractDB.ContractReservationControle(c.CompanyId);

                    if (ReservationControle == true)
                    {
                        int aantal = ContractDB.StopContract(c);
                        await this.ShowMessageAsync("Gestopt", "Het contract is gestopt!");
                        ContractLopendeGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsLopendUser(userID);
                        ContractAfgelopenGrid.ItemsSource = DataAccessLayer.ContractDB.GetContractsAfgelopenUser(userID);
                    }
                    else
                    {
                        await this.ShowMessageAsync("Fout!", "Het contract kan niet worden gestopt, omdat er nog reservaties zijn voor dit contract!");
                    }
                    
                }

                else
                {
                    await this.ShowMessageAsync("Niet Gestopt!", "Het contract is NIET gestopt!");
                }
            }


        }
        private void LogOutButton_Click(object sender, RoutedEventArgs e)
        {
            userID = null;
            MainWindow m = new MainWindow();
            this.Close();
            m.Show();          
        }

        private async void CalendarZalen_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                String date = CalendarZalen.SelectedDate.ToString();
                DatagridCalendarZalen.ItemsSource = DataAccessLayer.ReservationDB.GetReservationsDate(date);

                if (DatagridCalendarZalen.Items.Count == 0)
                {
                    await this.ShowMessageAsync("Geen zalen vrij!", "Op de geselecteerde datum zijn nog geen zalen beschikbaar.");
                }
            }
            catch (Exception ex)
            {
                string exception = "Je moet eerst een datum selecteren!";
                MessageBoxException(exception);
            }
        }

        private async void MessageBoxException(string ex)
        {
            await this.ShowMessageAsync("Fout!", ex);
        }
    }
}